<template>
  <div class="page-container">
    <div class="in-container">
      <el-row :gutter="8">
        <el-col :span="10">
          <AppTitleBox class="app-title-box" title="船名航次">
            <template #button>
              <el-button @click="openDialog()" link type="primary"
                >添加</el-button
              >
            </template>
            <AppSearchForm
              @submit="search()"
              @reset="reset()"
              size="small"
              labelWidth="auto"
            >
              <el-form-item>
                <el-input
                  v-model="state.query.KeyWords"
                  placeholder="输入航次名称"
                />
              </el-form-item>
            </AppSearchForm>
            <AppPageTable
              stripe
              :data="state.tableData.data"
              @change="getList()"
              :option="state.tableData.option"
              :singleHighLight="true"
              :autostyle="'height: calc(100% - 32px);'"
              @singleClick="(data) => singleClickGetDetail(data)"
            >
              <el-table-column type="selection" width="40" />
              <el-table-column
                :show-overflow-tooltip="true"
                prop="shipName"
                label="船名"
                width="140"
              />
              <el-table-column
                :show-overflow-tooltip="true"
                prop="voyageName"
                label="航次"
                width="140"
              />
              <el-table-column
                :show-overflow-tooltip="true"
                prop="levelNo"
                label="等级编号"
                width="140"
              />
              <el-table-column label="操作" width="150" fixed="right">
                <template #default="scope">
                  <el-button @click.stop="update(scope.row)" type="primary"
                    >编辑</el-button
                  >
                  <el-popconfirm
                    title="确定删除本条数据吗？"
                    @confirm="deleteData(scope.row)"
                  >
                    <template #reference>
                      <el-button type="danger">删除</el-button>
                    </template>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </AppPageTable>
          </AppTitleBox>
        </el-col>
        <el-col :span="14">
          <AppTitleBox class="app-title-box" title="挂港信息">
            <template #button>
              <el-button
                v-show="state.voyageDetailTableData.id"
                @click="openPortDialog()"
                link
                type="primary"
                >添加</el-button
              >
            </template>
            <div
              v-show="state.voyageDetailTableData.id"
              style="height: 100%"
            >
            <AppSearchForm
              @submit="getDetail()"
              @reset="portreset()"
              size="small"
              labelWidth="auto"
            >
              <el-form-item>
                <el-input v-model="state.portquery.KeyWords" placeholder="请输入" />
              </el-form-item>
            </AppSearchForm>

            <AppPageTable
              stripe
              :data="state.porttableData.data"
              @change="getDetail()"
              :option="state.porttableData.option"
              class="table"
            >
              <el-table-column type="selection" width="40" fixed="left" />

              <el-table-column
                :show-overflow-tooltip="true"
                prop="voyageName"
                label="航次"
                width="160"
              />
              <el-table-column
                :show-overflow-tooltip="true"
                prop="operationPort"
                label="操作港口"
                width="140"
              />
              <el-table-column
                :show-overflow-tooltip="true"
                prop="berthPort"
                label="靠泊港口"
                width="140"
              />
              <el-table-column
                :show-overflow-tooltip="true"
                prop="dateOfShipment"
                label="装船日期"
                width="140"
              />
              <el-table-column
                :show-overflow-tooltip="true"
                prop="expectedSailingDate"
                label="预计开航日期"
                width="140"
              />
              <el-table-column
                :show-overflow-tooltip="true"
                prop="sailingDate"
                label="实际开航日期"
                width="140"
              />
              <el-table-column
                :show-overflow-tooltip="true"
                prop="customsCloseDate"
                label="截关日期"
                width="140"
              />
              <el-table-column
                :show-overflow-tooltip="true"
                prop="portCloseDate"
                label="截港日期"
                width="140"
              />
              <el-table-column
                :show-overflow-tooltip="true"
                prop="expectedArrivalDate"
                label="预计到港日期"
                width="140"
              />
              <el-table-column
                :show-overflow-tooltip="true"
                prop="arrivalDate"
                label="实际到港日期"
                width="140"
              />
              <el-table-column
                :show-overflow-tooltip="true"
                prop="unloadingDate"
                label="卸港日期"
                width="140"
              />

              <el-table-column
                :show-overflow-tooltip="true"
                prop="isInLine"
                label="是否内支线"
                width="100"
              >
                <template #default="scope">
                  {{ scope.row.isInLine?'是':'否' }}
                </template>
              </el-table-column>

              <el-table-column
                :show-overflow-tooltip="true"
                prop="voyageFileNo"
                label="归档号"
                width="140"
              />

              <el-table-column
                :show-overflow-tooltip="true"
                prop="ieFlag"
                label="进出口标识"
                width="100"
              >
                <template #default="scope">
                  {{ scope.row.ieFlag == "I"?'进口':'出口' }}
                </template>
              </el-table-column>

              <el-table-column
                :show-overflow-tooltip="true"
                prop="levelNo"
                label="组织架构"
                width="100"
              />

              <el-table-column label="操作" width="150" fixed="right">
                <template #default="scope">
                  <el-button @click.stop="portupdate(scope.row)" type="primary"
                    >编辑</el-button
                  >
                  <el-popconfirm
                    title="确定删除本条数据吗？"
                    @confirm="portdeleteData(scope.row)"
                  >
                    <template #reference>
                      <el-button type="danger">删除</el-button>
                    </template>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </AppPageTable>
            </div>
            <div v-show="!state.voyageDetailTableData.id">
              点击航次查看挂港信息
            </div>
          </AppTitleBox>
        </el-col>
      </el-row>
      <!-- 船名航次 -->
      <el-dialog
        :title="state.dialogData.title"
        v-model="state.dialogData.show"
        width="400px"
      >
        <el-form
          :model="state.formData"
          :rules="state.formRules"
          label-width="80px"
          ref="form"
        >
          <el-form-item prop="shipId" label="船名">
            <el-select
              v-model="state.formData.shipId"
              filterable
              remote
              reserve-keyword
              placeholder="输入字符搜索"
              :remote-method="shipSelect"
              :loading="state.selectLoading"
              style="width: 100%"
            >
              <el-option
                v-for="item in state.selectOptions"
                :key="item.id"
                :label="item.nameEn"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="voyageName" label="航次">
            <el-input v-model="state.formData.voyageName"></el-input>
          </el-form-item>
          <!-- <el-form-item prop="levelNo" label="等级编号">
            <el-input v-model="state.formData.levelNo"></el-input>
          </el-form-item> -->
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancel" link>取消</el-button>
            <el-button type="primary" @click="submit"> 确认 </el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 挂港信息 -->
      <el-dialog
        :title="state.portdialogData.title"
        v-model="state.portdialogData.show"
        width="700px"
      >
        <el-form
          :model="state.portformData"
          :rules="state.portformRules"
          label-width="100px"
          ref="portform"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item prop="voyageId" label="航次">
                <el-input disabled v-model="state.voyageDetailTableData.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="operationPort" label="操作港口">
                <el-select
                  v-model="state.portformData.operationPort"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="输入字符搜索"
                  :remote-method="portSelect"
                  :loading="state.selectLoading"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in state.portOption"
                    :key="item.id"
                    :label="item.nameEn"
                    :value="item.nameEn"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="berthPort" label="靠泊港口">
                <el-select
                  v-model="state.portformData.berthPort"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="输入字符搜索"
                  :remote-method="portSelect"
                  :loading="state.selectLoading"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in state.portOption"
                    :key="item.id"
                    :label="item.nameEn"
                    :value="item.nameEn"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="dateOfShipment" label="装船日期">
                <el-date-picker
                  v-model="state.portformData.dateOfShipment"
                  type="datetime"
                  placeholder="请选择"
                  format="YYYY/MM/DD HH:mm:ss"
                  value-format="YYYY/MM/DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="expectedSailingDate" label="预计开航日期">
                <el-date-picker
                  v-model="state.portformData.expectedSailingDate"
                  type="datetime"
                  placeholder="请选择"
                  format="YYYY/MM/DD HH:mm:ss"
                  value-format="YYYY/MM/DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="sailingDate" label="实际开航日期">
                <el-date-picker
                  v-model="state.portformData.sailingDate"
                  type="datetime"
                  placeholder="请选择"
                  format="YYYY/MM/DD HH:mm:ss"
                  value-format="YYYY/MM/DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="customsCloseDate" label="截关日期">
                <el-date-picker
                  v-model="state.portformData.customsCloseDate"
                  type="datetime"
                  placeholder="请选择"
                  format="YYYY/MM/DD HH:mm:ss"
                  value-format="YYYY/MM/DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="portCloseDate" label="截港日期">
                <el-date-picker
                  v-model="state.portformData.portCloseDate"
                  type="datetime"
                  placeholder="请选择"
                  format="YYYY/MM/DD HH:mm:ss"
                  value-format="YYYY/MM/DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="expectedArrivalDate" label="预计到港日期">
                <el-date-picker
                  v-model="state.portformData.expectedArrivalDate"
                  type="datetime"
                  placeholder="请选择"
                  format="YYYY/MM/DD HH:mm:ss"
                  value-format="YYYY/MM/DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="arrivalDate" label="实际到港日期">
                <el-date-picker
                  v-model="state.portformData.arrivalDate"
                  type="datetime"
                  placeholder="请选择"
                  format="YYYY/MM/DD HH:mm:ss"
                  value-format="YYYY/MM/DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="unloadingDate" label="卸港日期">
                <el-date-picker
                  v-model="state.portformData.unloadingDate"
                  type="datetime"
                  placeholder="请选择"
                  format="YYYY/MM/DD HH:mm:ss"
                  value-format="YYYY/MM/DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="isInLine" label="是否内支线">
                <el-radio-group
                  v-model="state.portformData.isInLine"
                >
                  <el-radio :label="true">是</el-radio>
                  <el-radio :label="false">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="voyageFileNo" label="归档号">
                <el-input v-model="state.portformData.voyageFileNo"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="ieFlag" label="进出口标识">
                <el-select v-model="state.portformData.ieFlag">
                  <el-option label="进口" value="I"></el-option>
                  <el-option label="出口" value="E"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="levelNo" label="组织架构">
                <el-input v-model.number="state.portformData.levelNo"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="portcancel" link>取消</el-button>
            <el-button type="primary" @click="portsubmit"> 确认 </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  watch,
  computed,
  reactive,
  nextTick,
  defineEmits,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import request from "@/public/request";

import AppSearchForm from "@/components/AppSearchForm.vue";
import AppPageTable, { useTableOption } from "@/components/AppPageTable2";
import AppTitleBox from "@/components/AppTitleBox.vue";
import { fileDownload } from "@/public/publicUtils";

const state = reactive({
  query: {
    KeyWords: "",
  },
  portquery: {
    KeyWords: "",
  },
  tableData: {
    data: [],
    option: useTableOption(),
  },
  porttableData: {
    data: [],
    option: useTableOption(),
  },
  dialogData: {
    show: false,
    title: "",
    btnLoading: false,
  },
  formData: {
    shipId: "",
    voyageName: ""
  },
  formRules: {
    shipId: [{ required: true, message: "请选择船名", trigger: "change" }],
    voyageName: [{ required: true, message: "请输入航次", trigger: "change" }],
  },
  // 左侧主表删除按钮loading
  deleteBtnLoading: false,
  selectOptions: [],

  voyageDetailTableData: {
    id: null,
    name: ""
  },
  portdialogData: {
    show: false,
    title: "",
    btnLoading: false,
  },
  portformData: {
    voyageId: "",// 航次
    operationPort: "",// 操作港口
    berthPort: "",// 靠泊港口
    dateOfShipment: "",// 装船日期
    expectedSailingDate: "",// 预计开航日期
    sailingDate: "",// 实际开航日期
    customsCloseDate: "",// 截关日期
    portCloseDate: "",// 截港日期
    expectedArrivalDate: "",// 预计到港日期
    arrivalDate: "",// 实际到港日期
    unloadingDate: "",// 卸港日期
    isInLine: true,// 是否内支线
    voyageFileNo: "",// 归档号
    ieFlag: "",// 进出口标识
    levelNo: 0// 组织架构GUID
  },
  portformRules: {
    descriptionCh: [{ required: true, message: "请输入中文名", trigger: "change" }],
    descriptionEn: [{ required: true, message: "请输入英文名", trigger: "change" }],
  },
  selectLoading: false,
  portOption: []
});

const portform = ref();

const portupdate = (row) => {
  state.portdialogData.title = "编辑信息";
  state.portdialogData.show = true;
  nextTick(() => {
    state.portformData = JSON.parse(JSON.stringify(row));
  });
}

const portdeleteData = (data) => {
  request
    .post("/api/csvoyageport/delete", {
      idArray: [data.id],
    })
    .then((res) => {
      if (res.status) {
        ElMessage.success(res.message);
        getDetail();
      } else {
        ElMessage.error(res.message);
      }
    });
}

const portcancel = () => {
  state.portdialogData.show = false;
};
const portsubmit = async () => {
  state.portdialogData.btnLoading = true;
  let url = "";
  if (state.portformData.id) {
    url = "/api/csvoyageport/update";
  } else {
    url = "/api/csvoyageport/create";
  }
  state.portformData.voyageId = state.voyageDetailTableData.id;
  await portform.value.validate();
  request.post(url, state.portformData).then((res) => {
    if (res.status) {
      ElMessage.success(res.message);
      getDetail();
      state.portdialogData.show = false;
    } else {
      ElMessage.error(res.message);
    }
    state.portdialogData.btnLoading = false;
  });
}

const portSelect = (query) => {
  state.selectLoading = true;
  request
    .get("/api/csport/querypage", {
      KeyWords: query,
      PageIndex: 1,
      PageSize: 50,
    })
    .then((res) => {
      state.portOption = res.content;
    })
    .finally(() => {
      state.selectLoading = false;
    });
}

const singleClickGetDetail = (data) => {
  state.voyageDetailTableData.id = data.id;
  state.voyageDetailTableData.name = data.voyageName;
  getDetail();
};

const getDetail = async () => {
  state.porttableData.option.loading = true;
  request.get("/api/csvoyageport/querypage", {
      KeyWords: state.portquery.KeyWords,
      PageIndex: state.tableData.option.page,
      PageSize: state.tableData.option.pageSize,
      Id: state.voyageDetailTableData.id
    })
    .then((res) => {
      state.porttableData.data = res.content;
      state.porttableData.option.total = res.totalElements;
    })
    .finally(() => {
      state.porttableData.option.loading = false;
    });
};

const getList = () => {
  state.tableData.option.loading = true;
  request
    .get("/api/csvoyage/querypage", {
      VoyageName: state.query.KeyWords,
      PageIndex: state.tableData.option.page,
      PageSize: state.tableData.option.pageSize,
    })
    .then((res) => {
      state.tableData.data = res.content;
      state.tableData.option.total = res.totalElements;
    })
    .finally(() => {
      state.tableData.option.loading = false;
    });
};
const search = () => {
  state.tableData.option.page = 1;
  state.tableData.pageSize = 10;
  getList();
};
const reset = () => {
  state.query = {
    KeyWords: "",
  };
  state.tableData.option.page = 1;
  state.tableData.pageSize = 10;
  getList();
};
const portreset = () => {
  state.portquery = {
    KeyWords: "",
  };
  state.porttableData.option.page = 1;
  state.porttableData.pageSize = 10;
  getList();
}
const update = (item) => {
  state.dialogData.title = "编辑航次信息";
  state.dialogData.show = true;
  nextTick(() => {
    state.formData = JSON.parse(JSON.stringify(item));
  });
};

const deleteSelectData = () => {
  if (state.tableData.option.selected.length > 0) {
    let deleteArray = [];
    for (let i of state.tableData.option.selected) {
      deleteArray.push(i.id);
    }
    state.deleteBtnLoading = true;
    request
      .post("/api/csvoyage/delete", {
        idArray: deleteArray,
      })
      .then((res) => {
        if (res.status) {
          ElMessage.success(res.message);
          getList();
        } else {
          ElMessage.error(res.message);
        }
      })
      .finally(() => (state.deleteBtnLoading = false));
  } else {
    ElMessage.warning("请至少选择一条数据");
  }
};

const deleteData = (data) => {
  request
    .post("/api/csshippingterm/delete", {
      idArray: [data.id],
    })
    .then((res) => {
      if (res.status) {
        ElMessage.success(res.message);
        getList();
      } else {
        ElMessage.error(res.message);
      }
    });
};

const openDialog = () => {
  state.dialogData.title = "新增信息";
  state.dialogData.show = true;
};
const openPortDialog = () => {
  state.portdialogData.title = "新增挂港信息";
  state.portdialogData.show = true;
}
const form = ref();
const submit = async () => {
  state.dialogData.btnLoading = true;
  let url = "";
  if (state.formData.id) {
    url = "/api/csvoyage/update";
  } else {
    url = "/api/csvoyage/create";
  }
  await form.value.validate();
  request.post(url, state.formData).then((res) => {
    if (res.status) {
      ElMessage.success(res.message);
      getList();
      state.dialogData.show = false;
    } else {
      ElMessage.error(res.message);
    }
    state.dialogData.btnLoading = false;
  });
};
const cancel = () => {
  state.dialogData.show = false;
};

const shipSelect = (query) => {
  state.selectLoading = true;
  request
    .get("/api/csship/querypage", {
      KeyWords: query,
      PageIndex: 1,
      PageSize: 50,
    })
    .then((res) => {
      state.selectOptions = res.content;
    })
    .finally(() => {
      state.selectLoading = false;
    });
};

watch(
  () => state.dialogData.show,
  (newVal) => {
    if (!newVal) {
      state.formData = {
        shipId: "",
        voyageName: ""
      };
      nextTick(() => {
        form.value.resetFields();
      });
    }
  }
);

watch(
  () => state.portdialogData.show,
  (newVal) => {
    if (!newVal) {
      state.portformData = {
        voyageId: "",// 航次
        operationPort: "",// 操作港口
        berthPort: "",// 靠泊港口
        dateOfShipment: "",// 装船日期
        expectedSailingDate: "",// 预计开航日期
        sailingDate: "",// 实际开航日期
        customsCloseDate: "",// 截关日期
        portCloseDate: "",// 截港日期
        expectedArrivalDate: "",// 预计到港日期
        arrivalDate: "",// 实际到港日期
        unloadingDate: "",// 卸港日期
        isInLine: true,// 是否内支线
        voyageFileNo: "",// 归档号
        ieFlag: "",// 进出口标识
        levelNo: 0// 组织架构GUID
      }
      nextTick(() => {
        portform.value.resetFields();
      });
    }
  }
);

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.btn-area {
  margin-bottom: 8px;
}

.in-container {
  display: flex;
  flex-direction: column;
  height: 100%;

  .table {
    flex: 1;
  }
}

:deep(.date) {
  width: 100%;
}

.el-row {
  height: 100%;
}

.el-col {
  height: 100%;
}

.app-title-box {
  height: 100%;
  box-sizing: border-box;
}
</style>
